package cc.linker.steplink.crm.merchanth5.controller.acs;


import cc.linker.steplink.crm.merchanth5.service.acs.ExternalOrderService;
import cc.linker.steplink.crm.merchanth5.service.acs.OauthCheckH5Service;
import cc.linker.steplink.crm.merchanth5.service.redis.ScoreActiveCacheService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/h5/externalOrder")
public class ExternalOrderController {

    @Autowired
    private ExternalOrderService externalOrderService;
    @Autowired
    private OauthCheckH5Service oauthCheckService;
    @Autowired
    private ScoreActiveCacheService scoreActiveCacheService;

    /**
     *支付后获得订单详情
     * @return map
     */
    @PostMapping("/getOrder")
    public Map getOrder(@RequestBody Map<String, Object> param){
        String orderSn = null;
        if(param.get("orderSn")!=null){
            orderSn = param.get("orderSn").toString();
        }
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if(flag){
            return  externalOrderService.getOrder(orderSn);
        }else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }

    }

    /**
     *获取订单列表
     * @return map
     */
    @PostMapping("/getOrderList")
    public PageInfo<Map> getOrderList(@RequestBody Map<String, Object> param){
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        String startTime = null;
        int pageIndex = 1;
        int pageSize = 20;
        if(param.get("startTime")!=null && param.get("pageIndex")!=null && param.get("pageSize")!=null){
            startTime = param.get("startTime").toString();
            pageIndex = Integer.parseInt(param.get("pageIndex").toString());
            pageSize = Integer.parseInt(param.get("pageSize").toString());
        }else {
            throw GlobalException.build("参数错误");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if(flag){
            //return  externalOrderService.getOrder(orderSn);
            PageHelper.startPage(pageIndex, pageSize);
            return  new PageInfo<Map>(externalOrderService.getOrderList(startTime));
        }else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }
    }

    /**
     *退款发货获得发货信息
     * @return map
     */
    @PostMapping("/getRefundOrder")
    public Map getRefundOrder(@RequestBody Map<String, Object> param){
        Long recId = null;
        if(param.get("recId")!=null){
            recId =Long.valueOf(param.get("recId").toString());
        }
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if(flag){
            return  externalOrderService.getRefundOrder(recId);
        }else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }
    }


    /**
     *数据同步异常
     * @return map
     */
    @PostMapping("/addAbnormalReason")
    public void addAbnormalReason(@RequestBody Map<String, Object> param){
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if(flag){
            externalOrderService.addAbnormalReason(param);
        }else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }
    }


    /**
     * 订单结算完成通知
     * 通知触发条件：用户支付完成，完成结算之后。涉及字段：
     * （1）订单基础值：订单号，订单创建时间，订单支付时间，订单发货时间，商品总价，运费，订单总价，实付款，优惠抵扣金额（包含优惠券抵扣，或是其他满减类优惠），订单状态，配送状态
     * （2）订单商品明细值：订单号，商品名称，商品图片URL，商品单价，商品规格，商品数量
     * （3）付款会员信息值：手机号，昵称，头像，地区
     * （4）分享会员信息值：是否为分享订单，手机号，昵称，头像，地区
     * @param orderSn
     */
//    @RabbitListener(queues = ORDER_SUMMARY_END)
    public void summaryEnd(String orderSn){
        try{
            scoreActiveCacheService.invoke(orderSn);
            if(orderSn.startsWith("E")){
                scoreActiveCacheService.cacheOrderNum(orderSn);
            }
        }catch (Exception e){
            LOGGER.error("结算积分和成长值错误-结算订单",e);
            e.printStackTrace();
        }
        externalOrderService.summaryEnd(orderSn,0);
    }
//    @GetMapping("/testLm")
//    public void testLm(String orderSn){
//        externalOrderService.summaryEnd(orderSn,0);
//    }


    /**
     *通过手机号同步查询订单信息
     * @return PageInfo<Map>
     */
    @PostMapping("/getOrderListByPhone")
    public  PageInfo getOrderListByPhone(@RequestBody Map<String, Object> param){
        String phone = null;
        if(param.get("phone")!=null){
            phone = param.get("phone").toString();
        }
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        if(phone==null){
            throw GlobalException.build("手机号不能为空");
        }
        int pageIndex = 1;
        int pageSize = 20;
        if(param.get("pageIndex")!=null && param.get("pageSize")!=null){
            pageIndex = Integer.parseInt(param.get("pageIndex").toString());
            pageSize = Integer.parseInt(param.get("pageSize").toString());
        }else {
            throw GlobalException.build("参数错误");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if(flag){
            Map<String,Object> da = new HashMap<>();
            if(!StringUtils.isEmpty(param.get("startTime"))){
                da.put("startTime",param.get("startTime"));
            }
            if(!StringUtils.isEmpty(param.get("endTime"))){
                da.put("endTime",param.get("endTime"));
            }
            if(!StringUtils.isEmpty(param.get("orderState"))){
                da.put("orderState",param.get("orderState"));
            }
            da.put("phone",phone);
            return  externalOrderService.getOrderListByPhone(da,pageIndex, pageSize);
        }else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }

    }
}
